# Copyright 2021-2023 @ Shenzhen Bay Laboratory &
#                       Peking University &
#                       Huawei Technologies Co., Ltd
#
# This code is a part of Cybertron package.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""
Default configure for graph embedding
"""

import os
from typing import Union, Optional
from pathlib import Path

from ...utils import read_yaml


def get_embedding_config(configure: Union[str, dict, Path], key: Optional[str] = None) -> dict:
    """ Get embedding configuration from file or dictionary.

    Args:
        configure (Union[str, dict, Path]): Configuration file path or dictionary
        key (str, optional): Key to extract from configuration. Default: None

    Returns:
        dict: Configuration dictionary or extracted value for key

    Raises:
        ValueError: If configuration file not found
        TypeError: If configure is not str, Path or dict
        KeyError: If key not found in configuration
    """
    if configure is None:
        return configure

    if isinstance(configure, (str, Path)):
        if os.path.exists(configure):
            filename = configure
        else:
            directory = Path(__file__).parent
            filename = directory / configure
            if Path(configure).suffix != '.yaml':
                filename = filename.with_suffix('.yaml')
            if not os.path.exists(filename):
                raise ValueError(f'Cannot find configure file: {configure}')
        configure: dict = read_yaml(filename)

    if not isinstance(configure, dict):
        raise TypeError(f'The type of configure must be str, Path or dict but got: {type(configure)}')

    if key is not None:
        if key in configure:
            return configure[key]
        raise KeyError(f'Cannot find key "{key}" in configure.')

    return configure
